/*
 * Created: Author: Aléx Carvalho / Date: Jan 28, 2015
 * 
 * Changed: $Author: ac280593@gmail.com $ / $Date: 2015-06-05 00:26:28 +0000 (Fri, 05 Jun 2015) $
 */
package com.cpm.repository.jpa;

import com.cpm.ServiceLocator;
import com.cpm.entities.Competence;
import com.cpm.entities.Indicator;
import com.cpm.entities.types.IndicatorPeriodicity;
import com.cpm.repository.IndicatorRepository;
import java.time.LocalDate;
import java.time.temporal.TemporalAdjusters;
import java.util.ArrayList;
import java.util.List;

public class IndicatorRepositoryJpa extends GenericCrudRepositoryJpa<Indicator> implements IndicatorRepository {

    @Override
    public void postPersist(Indicator value) {

        LocalDate start = value.getDtStart();
        LocalDate end = value.getDtEnd();

        List<Competence> competences = new ArrayList<>();

        if (value.getPeriodicity() == IndicatorPeriodicity.MONTHTY) {

            for (int i = 0; true; i++) {
                LocalDate with = start.plusMonths(i).with(TemporalAdjusters.firstDayOfNextMonth());

                if (with.getMonthValue() > end.getMonthValue()) {
                    break;
                }

                Competence c = Competence.builder().indicator(value).competencePeriod(with).build();

                competences.add(c);
            }
        }

        ServiceLocator.getCompetenceRepository().persistList(competences);
    }
}
